#include "Weather_Forecast.h"
#include "citydata.h"
#include "weather_icon.h"
#include "AQI.h"
#include "NavigationController.h"

#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonArray>

#include <QPixmap>
#include <QPainter>
#include <QPen>
#include <QLabel>
#include <QPalette>
#include <QBrush>
#include <QColor>

#define penWidth 1
#define Point_Radius 3
#define Text_OFFSETX 12
#define Text_OFFSETY 12
#define OFFSETPERTEMP 3

Weather_Forecast::Weather_Forecast(QWidget *parent)
    : QWidget(parent), ui(new Ui::Weather_Forecast)
{
    ui->setupUi(this);

    // this->setStyleSheet("background-image : url(:/icons/background.png);\nbackground-repeat: no-repeat;\nbackground-position: cneter;\n background-size: cover;\n");

    setWindowTitle("Weather Forecast");

    provinces = getProvinces();
    for(auto &p : provinces)
        ui->provinceSelectBox->addItem(p.provinceName);
    ui->provinceSelectBox->setCurrentText(provinces.front().provinceName);

    typewordLabel[0] = ui->word_0; typewordLabel[1] = ui->word_1; typewordLabel[2] = ui->word_2; typewordLabel[3] = ui->word_3; typewordLabel[4] = ui->word_4; typewordLabel[5] = ui->word_5; typewordLabel[6] = ui->word_6;
    typeiconLabel[0] = ui->iconlabel_0; typeiconLabel[1] = ui->iconlabel_1; typeiconLabel[2] = ui->iconlabel_2; typeiconLabel[3] = ui->iconlabel_3; typeiconLabel[4] = ui->iconlabel_4; typeiconLabel[5] = ui->iconlabel_5; typeiconLabel[6] = ui->iconlabel_6;
    date[0] = ui->date_0; date[1] = ui->date_1;  date[2] = ui->date_2;  date[3] = ui->date_3;  date[4] = ui->date_4;  date[5] = ui->date_5;  date[6] = ui->date_6;
    wind[0] = ui->wind_0; wind[1] = ui->wind_1; wind[2] = ui->wind_2; wind[3] = ui->wind_3;  wind[4] = ui->wind_4; wind[5] = ui->wind_5; wind[6] = ui->wind_6;
    air[0] = ui->air_0;  air[1] = ui->air_1;  air[2] = ui->air_2;  air[3] = ui->air_3;  air[4] = ui->air_4;  air[5] = ui->air_5;  air[6] = ui->air_6;

    this->setWindowTitle("Weather Forecast");

    ui->HighCurveLabel->installEventFilter(this);
    ui->LowCurveLabel->installEventFilter(this);

    on_pushButton_clicked();
}

Weather_Forecast::~Weather_Forecast()
{
    delete ui;
}

bool Weather_Forecast::eventFilter(QObject *watched, QEvent *event)
{
    if(watched == ui->HighCurveLabel && event->type() == QEvent::Paint) {
        paintHighCurve();
    }
    if(watched == ui->LowCurveLabel && event->type() == QEvent::Paint) {
        paintLowCurve();
    }
    return QWidget::eventFilter(watched, event);
}

void Weather_Forecast::paintHighCurve()
{
    int x[7] = {};
    for(int i = 0; i < 7; i++) {
        x[i] = date[i]->pos().x() + date[i]->width() / 2;
    }

    int y_sum = 0;
    double y_avg;
    double ycenter = ui->HighCurveLabel->height() / 2;
    int y[7] = {};
    for(int i = 0; i < 7; i++) {
        y_sum += highTemp[i];
    }
    y_avg = y_sum / 7;
    for(int i = 0; i < 7; i++) {
        y[i] = ycenter - ((highTemp[i] - y_avg) * OFFSETPERTEMP);
    }

    QPainter painter(ui->HighCurveLabel);
    painter.setRenderHint(QPainter::Antialiasing, true);

    QPen pen = painter.pen();
    pen.setWidth(penWidth);

    pen.setColor(QColor(255, 170, 0));
    painter.setBrush(QColor(255, 170, 0));
    painter.setPen(pen);

    for(int i = 0; i < 7; i++) {
        painter.drawEllipse(QPoint(x[i], y[i]), Point_Radius, Point_Radius);
        painter.drawText(QPoint(x[i]-Text_OFFSETX, y[i]-Text_OFFSETY), highTempStr[i]);
    }

    pen.setStyle(Qt::DotLine);
    painter.setPen(pen);
    painter.drawLine(x[0], y[0], x[1], y[1]);

    pen.setStyle(Qt::SolidLine);
    painter.setPen(pen);
    for(int i = 1; i < 6; i++) {
        painter.drawLine(x[i], y[i], x[i+1], y[i+1]);
    }
}

void Weather_Forecast::paintLowCurve()
{
    int x[7] = {};
    for(int i = 0; i < 7; i++) {
        x[i] = date[i]->pos().x() + date[i]->width() / 2;
    }

    int y_sum = 0;
    double y_avg;
    double ycenter = ui->LowCurveLabel->height() / 2;
    int y[7] = {};
    for(int i = 0; i < 7; i++) {
        y_sum += lowTemp[i];
    }
    y_avg = y_sum / 7;
    for(int i = 0; i < 7; i++) {
        y[i] = ycenter - ((lowTemp[i] - y_avg) * OFFSETPERTEMP);
    }

    QPainter painter(ui->LowCurveLabel);
    painter.setRenderHint(QPainter::Antialiasing, true);

    QPen pen = painter.pen();
    pen.setWidth(penWidth);

    pen.setColor(QColor(0, 255, 255));
    painter.setBrush(QColor(0, 255, 255));
    painter.setPen(pen);

    for(int i = 0; i < 7; i++) {
        painter.drawEllipse(QPoint(x[i], y[i]), Point_Radius, Point_Radius);
        painter.drawText(QPoint(x[i]-Text_OFFSETX, y[i]-Text_OFFSETY), lowTempStr[i]);
    }

    pen.setStyle(Qt::DotLine);
    painter.setPen(pen);
    painter.drawLine(x[0], y[0], x[1], y[1]);

    pen.setStyle(Qt::SolidLine);
    painter.setPen(pen);
    for(int i = 1; i < 6; i++) {
        painter.drawLine(x[i], y[i], x[i+1], y[i+1]);
    }
}

void Weather_Forecast::on_pushButton_clicked()
{
    qDebug() << "front\n";
    QString cityCode = getCityCodeByName(ui->citySelectBox->currentText());
    // qDebug() << "cityName: " << ui->citySelectBox->currentText() << " cityCode: " << cityCode;
    QNetworkAccessManager *manager = new QNetworkAccessManager(this);   //网络管理器
    QNetworkRequest request;   //请求
    request.setUrl(QUrl("http://t.weather.itboy.net/api/weather/city/" + cityCode));   //设置url
    QNetworkReply *reply = manager->get(request); //发送get请求
    connect(reply, &QNetworkReply::finished, [=](){   //请求完成后的处理
        if(reply->error() == QNetworkReply::NoError)
        {
            QByteArray data = reply->readAll();
            QJsonParseError json_error;
            QJsonDocument doc = QJsonDocument::fromJson(data, &json_error);  //解析json数据
            if(json_error.error == QJsonParseError::NoError)
            {
                if(doc.isObject())
                {
                    QJsonObject obj = doc.object();  //获取json对象
                    if(obj.contains("data"))  //判断是否包含data
                    {
                        QJsonValue value = obj.value("data");  //获取data数据
                        if(value.isObject())
                        {
                            QString windText[7] = {"", "", "", "", "", "", ""};

                            QJsonObject data = value.toObject();  //获取data对象
                            QJsonArray forecast = data["forecast"].toArray();
                            QJsonObject forecastObj[7] = {};

                            QString weekdate[7] ={"昨天\n", "今天\n", "明天\n", "", "", "", ""};
                            QString todayDetailText = "";

                            forecastObj[0] = data["yesterday"].toObject();
                            for(int i = 0; i < 6; i++) forecastObj[i+1] = forecast[i].toObject();

                            QString city = "查询：" + ui->provinceSelectBox->currentText();
                            if(ui->provinceSelectBox->currentText() != ui->citySelectBox->currentText()) city += ui->citySelectBox->currentText();
                            ui->city->setText(city);
                            ui->todayTempLabel->setText(ui->citySelectBox->currentText());

                            for(int i = 0; i < 7; i++) {
                                if(forecastObj[i].contains("type")) {
                                    // typewordLabel[i] = new QLabel(this);
                                    typewordLabel[i]->setText(forecastObj[i]["type"].toString());
                                    typewordLabel[i]->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                                    // ui->word_tH->addWidget(typewordLabel[i]);

                                    QString iconpath = ":/icon/" + getIconPath(forecastObj[i]["type"].toString());
                                    QPixmap pixmap(iconpath);
                                    // typeiconLabel[i] = new QLabel(this);
                                    typeiconLabel[i]->setPixmap(pixmap); // 设置图片到QLabel
                                    typeiconLabel[i]->setScaledContents(true);
                                    // ui->icon_tH->addWidget(typeiconLabel[i]);
                                }
                                if(forecastObj[i].contains("fx")) {
                                    // wind[i] = new QLabel(this);
                                    windText[i] += forecastObj[i]["fx"].toString() + '\n';
                                }
                                if(forecastObj[i].contains("fl")) {
                                    windText[i] += forecastObj[i]["fl"].toString();
                                    wind[i]->setText(windText[i]);
                                    wind[i]->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                                    // ui->wind_H->addWidget(wind[i]);
                                }
                                if(forecastObj[i].contains("aqi")) {
                                    // air[i] = new QLabel(this);
                                    int num = forecastObj[i]["aqi"].toInt();
                                    air[i]->setText(getAqi(num, air[i]));
                                    air[i]->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                                    // ui->air_H->addWidget(air[i]);
                                }
                                if(forecastObj[i].contains("ymd")) {
                                    if(i >= 3 && forecastObj[i].contains("week")) {
                                        weekdate[i] += forecastObj[i]["week"].toString() +'\n';
                                    }
                                    QStringList md = forecastObj[i]["ymd"].toString().split('-');
                                    weekdate[i] += md[1] + '/';
                                    weekdate[i] += md[2];
                                    // date[i] = new QLabel(this);
                                    date[i]->setText(weekdate[i]);
                                    date[i]->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                                    // ui->date_H->addWidget(date[i]);
                                }
                                if(forecastObj[i].contains("high")) {
                                    QString temp = forecastObj[i]["high"].toString().split(' ')[1];
                                    highTempStr[i] = temp;
                                    qDebug() << "here1\n";
                                    highTemp[i] = temp.split("℃")[0].toInt();
                                    qDebug() << "here2\n";
                                }
                                if(forecastObj[i].contains("low")) {
                                    QString temp = forecastObj[i]["low"].toString().split(' ')[1];
                                    lowTempStr[i] = temp;
                                    qDebug() << "here3\n";
                                    lowTemp[i] = temp.split("℃")[0].toInt();
                                    qDebug() << "here4\n";
                                }
                            }

                            if(forecastObj[1].contains("week") && forecastObj[1].contains("ymd"))
                                ui->currentDate->setText(forecastObj[1]["ymd"].toString() + ' ' + forecastObj[0]["week"].toString());

                            ui->HighCurveLabel->update();
                            ui->LowCurveLabel->update();

                            todayDetailText += typewordLabel[1]->text() + "  " + lowTempStr[1] + '~' + highTempStr[1];
                            ui->today_detail->setAlignment(Qt::AlignCenter | Qt::AlignVCenter);
                            ui->today_detail->setText(todayDetailText);
                            ui->searchcityLabel->setText(ui->citySelectBox->currentText());

                            if(data.contains("ganmao")) {
                                ui->noticeLabel->setText("  感冒指数：" + data["ganmao"].toString());
                            }

                            QString path = ":icon/" + getIconPath(forecastObj[1]["type"].toString());
                            QPixmap p(path);
                            ui->todaytemp->setPixmap(p);
                            ui->todaytemp->setScaledContents(true);

                            if(data.contains("wendu"))   //判断是否包含wendu
                            {
                                QJsonValue wendu = data.value("wendu");   //获取温度
                                ui->todayTempLabel->setText(wendu.toString() + "℃");
                            }


                            QString iconpath = ":/icon/weathercock.png";
                            QPixmap pixmap(iconpath);
                            ui->icon_1->setPixmap(pixmap);
                            ui->icon_1->setScaledContents(true);
                            ui->detail_1->setText(wind[1]->text());

                            iconpath = ":/icon/pm25.png";
                            QPixmap pixmap1(iconpath);
                            ui->icon_2->setPixmap(pixmap1);
                            ui->icon_2->setScaledContents(true);
                            QJsonValue pm25 = data.value("pm25");
                            ui->detail_2->setText(QString("pm2.5\n%1").arg(pm25.toDouble()));

                            iconpath = ":/icon/dew.png";
                            QPixmap pixmap2(iconpath);
                            ui->icon_3->setPixmap(pixmap2);
                            ui->icon_3->setScaledContents(true);
                            QJsonValue shidu = data.value("shidu");   //获取温度
                            ui->detail_3->setText("湿度\n" + shidu.toString());

                            iconpath = ":/icon/leaf.png";
                            QPixmap pixmap3(iconpath);
                            ui->icon_4->setPixmap(pixmap3);
                            ui->icon_4->setScaledContents(true);
                            ui->detail_4->setText("空气质量\n" + air[1]->text());
                        }
                    }
                }
            }
        }
        reply->deleteLater();  //释放资源
        // delete typewordLabel;
    });
}

void Weather_Forecast::on_provinceSelectBox_currentTextChanged(const QString &str)
{
    for(auto &p : provinces) if(p.provinceName == str)
        {
            ui->citySelectBox->clear();
            for(auto &c : p.citys)
                ui->citySelectBox->addItem(c.cityName);
            break;
        }
}

void Weather_Forecast::on_citySelectBox_currentTextChanged(const QString &cityName)
{
    QString cityCode = getCityCodeByName(cityName);
}

void Weather_Forecast::on_pushButton_2_clicked()
{
    MyNavigationController::instance().backToMainPage();
}

